package com.xindaoapp.happypet.ui;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.XDHttpClient;
import com.xindaoapp.happypet.activity.PrivateLetterActivity;
import com.xindaoapp.happypet.activity.PushMessageActivity;
import com.xindaoapp.happypet.adapter.MessageCenterAdapter2;
import com.xindaoapp.happypet.adapter.MessageCenterAdapter2.MESSAGETYPE;
import com.xindaoapp.happypet.adapter.MessageCenterAdapter2.ViewHolder;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.MessageCenterInfo;
import com.xindaoapp.happypet.bean.MyMessageInfo;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.xdConfig;

/**
 * 我的消息中心 最新
 * 
 */
public class MyMessageFragment extends BaseFragment {



    public MyMessageFragment() {
        super();
        // TODO Auto-generated constructor stub
    }

    public static MyMessageFragment newInstance() {
        MyMessageFragment fragment = new MyMessageFragment();
        return fragment;
    }

    private ImageView vImageViewLingdang;
    private PullToRefreshListView mlistview;
    private View mNoData;

    private View vHeader;
    private RelativeLayout vLay1, vLay2, vLay3;
    private ImageView vPoint1, vPoint2, vPoint3;
    private TextView vCount1, vCount2, vCount3;
    private ImageView iv_back;



    private ReceiveJpush mReceiveJpush;
    private AudioButtonJpush mAudioButtonJpush;

    private boolean mFrist = true;



    private MessageCenterAdapter2 mAdapter;

    private MessageCenterInfo info1 = null;
    private MessageCenterInfo info2 = null;
    private MessageCenterInfo info3 = null;

    private boolean isCheckOn;

    List<MessageCenterInfo> list = new ArrayList<MessageCenterInfo>();

    MessageCenterInfo mSysInfo, mReplyInfo;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return mView = inflater.inflate(R.layout.fragment_mymessage, container, false);
    }

    @Override
    protected void initViews() {

        mReceiveJpush = new ReceiveJpush();
        getActivity().registerReceiver(mReceiveJpush,
                new IntentFilter(Constants.ACTION_RECEIVED_NOTICE));
        mAudioButtonJpush = new AudioButtonJpush();
        getActivity().registerReceiver(mAudioButtonJpush,
                new IntentFilter(Constants.ACTION_AUDIO_SETTING_CHANGED));

        iv_back = (ImageView) mView.findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                ((Activity) mContext).finish();
            }
        });
        mNoData = mView.findViewById(R.id.no_data);
        vImageViewLingdang = (ImageView) mView.findViewById(R.id.right_icon);
        mlistview = (PullToRefreshListView) mView.findViewById(R.id.listview);
        mlistview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        mlistview.setOnRefreshListener(mOnRefreshListener);
        mlistview.getRefreshableView().setOnItemClickListener(mOnItemClickListener);
        mlistview.getRefreshableView().setOnItemLongClickListener(mItemLongClickListener);

        LayoutInflater inflater =
                (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        vHeader = inflater.inflate(R.layout.item_mymessage_headview, null);
        // 系统通知
        vLay1 = (RelativeLayout) vHeader.findViewById(R.id.relativeLayout1);
        // vSystem = (ImageView) vHeader.findViewById(R.id.iv_system);
        vPoint1 = (ImageView) vHeader.findViewById(R.id.red_point1);
        vCount1 = (TextView) vHeader.findViewById(R.id.count1);
        // vContent = (TextView) vHeader.findViewById(R.id.tv_content);
        // 回复我的
        vLay2 = (RelativeLayout) vHeader.findViewById(R.id.relativeLayout2);
        // vReply = (ImageView) vHeader.findViewById(R.id.iv_reply);
        vPoint2 = (ImageView) vHeader.findViewById(R.id.red_point2);
        vCount2 = (TextView) vHeader.findViewById(R.id.count2);
        // vContent2 = (TextView) vHeader.findViewById(R.id.tv_content2);
        // @我的
        vLay3 = (RelativeLayout) vHeader.findViewById(R.id.relativeLayout3);
        // vAt = (ImageView) vHeader.findViewById(R.id.iv_at);
        vPoint3 = (ImageView) vHeader.findViewById(R.id.red_point3);
        vCount3 = (TextView) vHeader.findViewById(R.id.count3);
        // vContent3 = (TextView) vHeader.findViewById(R.id.tv_content3);


        // vLine1 = (TextView) mView.findViewById(R.id.lineone);
        // vLine2 = (TextView) mView.findViewById(R.id.linetwo);
        // vLine3 = (TextView) mView.findViewById(R.id.linethree);
        // vLine4 = (TextView) mView.findViewById(R.id.lineend);


        mlistview.getRefreshableView().addHeaderView(vHeader);
        mlistview.getRefreshableView().setAdapter(null);
        super.initViews();
    }

    private final OnRefreshListener<ListView> mOnRefreshListener =
            new OnRefreshListener<ListView>() {

                @Override
                public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                    loadDatas();
                }
            };

    private final OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            MessageCenterInfo info = (MessageCenterInfo) parent.getAdapter().getItem(position);
            if (info != null && view.getTag() != null) {
                handleOnClick(info, ((ViewHolder) view.getTag()).isNew,
                        ((ViewHolder) view.getTag()).count);
            }

        }
    };

    private final OnItemLongClickListener mItemLongClickListener = new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(final AdapterView<?> parent, View arg1, final int position,
                long arg3) {
            new AlertDialog.Builder(mContext).setTitle("私信").setMessage("确认删除？")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            MessageCenterInfo info =
                                    (MessageCenterInfo) parent.getAdapter().getItem(position);
                            String id = info.id;
                            delete(position, id);
                        }
                    }).create().show();
            return false;
        }
    };

    private void delete(final int position, String noticeId) {
        getMoccaApi().deleteInformMessage(noticeId, new IRequest<Pair<Boolean, String>>() {

            @Override
            public void request(Pair<Boolean, String> t) {


                if (null != t) {
                    if (t.first) {
                        mAdapter.getResult().remove(position - 2);
                        mAdapter.notifyDataSetChanged();
                    }
                    Toast.makeText(mContext, t.second, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(mContext, R.string.net_error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void handleOnClick(MessageCenterInfo info, View isNew, TextView count) {

        if (info.type.equals(MESSAGETYPE.APP_PM.type)) {
            Intent i = new Intent(getActivity(), PrivateLetterActivity.class);
            i.putExtra(Constants.KEY_TOUID, info.authorid);
            i.putExtra(Constants.KEY_USERNAME, info.author);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getActivity().startActivity(i);
        }

        if (info.isnew == 1) {
            info.isnew = 0;
            count.setText("");
            isNew.setVisibility(View.GONE);
            HappyPetApplication.get().getMoccaApi().noticeClick(info.id, new IRequest<Boolean>() {

                @Override
                public void request(Boolean t) {
                    if (t) {
                        Constants.NoticeLabel.sHasNewMessageNotice = true;
                    } else {
                        Constants.NoticeLabel.sHasNewMessageNotice = false;
                    }
                    Intent notice = new Intent(Constants.KEY_NOTICE_STATE_CHANGED);
                    getActivity().sendBroadcast(notice);
                }
            });
        }
    }

    @Override
    protected void initEvents() {

        vImageViewLingdang.setOnClickListener(mRightIconListener);

        vLay1.setOnClickListener(mSystemListener);
        vLay2.setOnClickListener(mReplyListener);
        vLay3.setOnClickListener(mAtListener);

        super.initEvents();
    }

    @Override
    protected void loadDatas() {

        // getMoccaApi().getMyMessageInfo(Constants.PAGE_FIRST, Constants.PAGE_SIZE,
        // 测试分页情况

        getMessageInfo();

        getPushAuSwitch();



        super.loadDatas();
    }



    private void getPushAuSwitch() {
        getPushAudioSwitch(new IRequest<Boolean>() {

            @Override
            public void request(Boolean t) {

                // mlistview.onRefreshComplete();

                isCheckOn = t;
                if (t) {
                    vImageViewLingdang.setImageResource(R.drawable.bt_lingdang);
                } else {
                    vImageViewLingdang.setImageResource(R.drawable.bt_lingdang_off);
                }
            }
        });
    }

    private void getMessageInfo() {

        if (CommonUtil.checkNetState(mContext)) {
            getMoccaApi().getMyMessageInfo(Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                    new IRequest<MyMessageInfo>() {

                        @Override
                        public void request(MyMessageInfo t) {

                            mlistview.onRefreshComplete();

                            if (t != null) {
                                mFrist = false;
                                onDataArrived(true);


                                if (Integer.parseInt(t.getIsnew().trim()) > 0) {
                                    Constants.NoticeLabel.sHasNewMessageNotice = true;
                                    Intent notice = new Intent(Constants.KEY_NOTICE_STATE_CHANGED);
                                    mContext.sendBroadcast(notice);
                                } else {
                                    Constants.NoticeLabel.sHasNewMessageNotice = false;
                                    Intent notice = new Intent(Constants.KEY_NOTICE_STATE_CHANGED);
                                    mContext.sendBroadcast(notice);
                                }

                                if (t.getArray().size() == 0 && t.getCatearray().size() == 0) {
                                    mNoData.setVisibility(View.VISIBLE);
                                } else {
                                    mNoData.setVisibility(View.GONE);
                                    mAdapter =
                                            new MessageCenterAdapter2(mContext, t.getArray(),
                                                    Constants.PAGE_SIZE,
                                                    R.layout.item_message_center_new,
                                                    // Constants.PAGE_SIZE,
                                                    // R.layout.item_message_center2,
                                                    R.layout.item_loading);
                                    mlistview.getRefreshableView().setAdapter(mAdapter);
                                }

                                if (t.getCatearray().size() != 0) {

                                    MessageCenterInfo info;

                                    for (int i = 0; i < t.getCatearray().size(); i++) {

                                        info = t.getCatearray().get(i);

                                        if (info.type.equals(MESSAGETYPE.SYSTEM.type)) {
                                            info1 = info;
                                            SpannableStringBuilder ssb =
                                                    CommonUtil.convetToHtml(
                                                            CommonUtil.parseEmoji(info.message),
                                                            mContext);
                                            // vContent.setText(ssb);
                                            if (info.isnew == 1) {
                                                vCount1.setVisibility(View.VISIBLE);
                                                vPoint1.setVisibility(View.VISIBLE);
                                                vCount1.setText(String
                                                        .valueOf(info.from_num > 99 ? "99+"
                                                                : info.from_num));
                                            } else {
                                                vCount1.setVisibility(View.GONE);
                                                vPoint1.setVisibility(View.GONE);
                                            }


                                        } else if (info.type.equals(MESSAGETYPE.POST.type)) {
                                            info2 = info;
                                            // vContent2.setText(info.author + " 回复了您");
                                            if (info.isnew == 1) {
                                                vCount2.setVisibility(View.VISIBLE);
                                                vPoint2.setVisibility(View.VISIBLE);
                                                vCount2.setText(String
                                                        .valueOf(info.from_num > 99 ? "99+"
                                                                : info.from_num));
                                            } else {
                                                vCount2.setVisibility(View.GONE);
                                                vPoint2.setVisibility(View.GONE);
                                            }


                                        } else if (info.type.equals(MESSAGETYPE.AT.type)) {
                                            info3 = info;
                                            // vContent3.setText(info.author + " @了您");
                                            if (info.isnew == 1) {
                                                vCount3.setVisibility(View.VISIBLE);
                                                vPoint3.setVisibility(View.VISIBLE);
                                                vCount3.setText(String
                                                        .valueOf(info.from_num > 99 ? "99+"
                                                                : info.from_num));
                                            } else {
                                                vCount3.setVisibility(View.GONE);
                                                vPoint3.setVisibility(View.GONE);
                                            }


                                        }

                                    }

                                    // if (info1 == null) {
                                    // vLay1.setVisibility(View.GONE);
                                    // vLine2.setVisibility(View.GONE);
                                    // }
                                    // if (info2 == null) {
                                    // vLay2.setVisibility(View.GONE);
                                    // vLine3.setVisibility(View.GONE);
                                    // }
                                    // if (info3 == null) {
                                    // vLay3.setVisibility(View.GONE);
                                    // vLine4.setVisibility(View.GONE);
                                    // }

                                } else {

                                    // vHeader.setVisibility(View.GONE);

                                    // vLay1.setVisibility(View.GONE);
                                    // vLine2.setVisibility(View.GONE);
                                    // vLay2.setVisibility(View.GONE);
                                    // vLine3.setVisibility(View.GONE);
                                    // vLay3.setVisibility(View.GONE);
                                    // vLine4.setVisibility(View.GONE);

                                }


                            } else {

                                // mlistview.onRefreshComplete();

                                if (mFrist) {
                                    onDataArrived(false);
                                    load_fail.setOnClickListener(new OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            startAnimation();
                                            loadDatas();
                                        }
                                    });
                                }
                            }


                        }
                    });
        } else {

            HappyPetApplication.mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub

                    mlistview.onRefreshComplete();
                }
            }, 300);


            if (mFrist) {
                onDataArrived(false);
                load_fail.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startAnimation();
                        loadDatas();
                    }
                });
            }
            Toast.makeText(mContext, R.string.pLease_check_network, Toast.LENGTH_SHORT).show();

        }

    }

    private final OnClickListener mSystemListener = new OnClickListener() {

        @Override
        public void onClick(View arg0) {



            if (UserState.isLogged()) {


                Intent intent = new Intent(getActivity(), MySystemInfoListActivity.class);
                startActivity(intent);

                if (info1 != null) {

                    if (info1.isnew == 1) {
                        info1.isnew = 0;
                        vCount1.setText("");
                        vPoint1.setVisibility(View.GONE);
                        HappyPetApplication.get().getMoccaApi()
                                .noticeClick(info1.id, new IRequest<Boolean>() {

                                    @Override
                                    public void request(Boolean t) {
                                        if (t) {
                                            Constants.NoticeLabel.sHasNewMessageNotice = true;
                                        } else {
                                            Constants.NoticeLabel.sHasNewMessageNotice = false;
                                        }
                                        Intent notice =
                                                new Intent(Constants.KEY_NOTICE_STATE_CHANGED);
                                        getActivity().sendBroadcast(notice);
                                    }
                                });
                    }
                }


            }

        }
    };
    private final OnClickListener mReplyListener = new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent i = new Intent(getActivity(), MyReplyInfoListActivity.class);
            getActivity().startActivity(i);
            if (UserState.isLogged()) {

                if (info2 != null) {
                    if (info2.isnew == 1) {
                        info2.isnew = 0;
                        vCount2.setText("");
                        vPoint2.setVisibility(View.GONE);
                        HappyPetApplication.get().getMoccaApi()
                                .noticeClick(info2.id, new IRequest<Boolean>() {


                                    @Override
                                    public void request(Boolean t) {
                                        if (t) {
                                            Constants.NoticeLabel.sHasNewMessageNotice = true;
                                        } else {
                                            Constants.NoticeLabel.sHasNewMessageNotice = false;
                                        }
                                        Intent notice =
                                                new Intent(Constants.KEY_NOTICE_STATE_CHANGED);
                                        getActivity().sendBroadcast(notice);
                                    }
                                });
                    }
                }
            }

        }
    };
    private final OnClickListener mAtListener = new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            startActivity(new Intent(getActivity(), MyAtInfoListActivity.class));
            if (UserState.isLogged()) {

                if (info3 != null) {
                    if (info3.isnew == 1) {
                        info3.isnew = 0;
                        vCount2.setText("");
                        vPoint3.setVisibility(View.GONE);
                        HappyPetApplication.get().getMoccaApi()
                                .noticeClick(info3.id, new IRequest<Boolean>() {

                                    @Override
                                    public void request(Boolean t) {
                                        if (t) {
                                            Constants.NoticeLabel.sHasNewMessageNotice = true;
                                        } else {
                                            Constants.NoticeLabel.sHasNewMessageNotice = false;
                                        }
                                        Intent notice =
                                                new Intent(Constants.KEY_NOTICE_STATE_CHANGED);
                                        getActivity().sendBroadcast(notice);
                                    }
                                });
                    }
                }

            }

        }
    };


    private final OnClickListener mRightIconListener = new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if (UserState.isLogged()) {
                startActivity(new Intent(getActivity(), PushMessageActivity.class));
            }

        }
    };

    class AudioButtonJpush extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getBooleanExtra(Constants.KEY_AUDIO_SETTING, true)) {
                isCheckOn = true;
                vImageViewLingdang.setImageResource(R.drawable.bt_lingdang);
            } else {
                isCheckOn = false;
                vImageViewLingdang.setImageResource(R.drawable.bt_lingdang_off);
            }
        }

    }

    class ReceiveJpush extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            loadDatas();
        }

    }

    /**
     * 获取推送声音开关
     * 
     * @param iRequest
     */
    private void getPushAudioSwitch(final IRequest<Boolean> iRequest) {
        RequestParams params = new RequestParams();
        XDHttpClient.post(xdConfig.PUSHMESSAGE, params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                super.onSuccess(statusCode, content);
                try {
                    iRequest.request(new JSONObject(content).getJSONObject("info")
                            .getInt("isaudio") == 1 ? true : false);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mReceiveJpush);
        getActivity().unregisterReceiver(mAudioButtonJpush);
    }


}
